package com.wanho.qz103.hrsaas.commons.util;

import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 实现 用户密码 加密
 */
public class MD5Util {
    /**转的key 字符*/
    private static String[] KEY_AR= {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"} ;

    /**
     *  把一个 字节byte 转成 String
     * @param b  字节
     * @return  上面数组中 取 2 个元素
     */
    private static String byteToString(byte b){
        // byte  -128~127
        int k = b ;
        if (b<0){
            k = b+256;
        }
        return KEY_AR[k/16]+ KEY_AR[k%16] ;
    }

    private static String byteArrrayToString(byte[] ay){
        StringBuilder sb = new StringBuilder() ;
        for (byte b : ay) {
            sb.append(byteToString(b)) ;
        }
        return sb.toString() ;
    }

    /**
     * 加密
     * @param password  明文密码
     * @param salt      盐值   一出生生成随机字符串 唯一的  新增员工 生成
     * @return
     */
    public static String md5(String password ,String salt){
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] digest = messageDigest.digest((password + salt).getBytes());
            //return new String(digest);
            return byteArrrayToString(digest) ;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage()) ;
        }
    }
}
